from typing import List, Optional
from sqlalchemy.orm import Session
from datetime import datetime

from models.SignApplyInfoModel import SignApplyInfo
from schemas.SignApplyInfo import SignApplyInfoCreate, SignApplyInfoUpdate

class SignApplyInfoServe:
    @staticmethod
    def create(db: Session, sign_apply_info: SignApplyInfoCreate) -> SignApplyInfo:
        """创建签到申请信息"""
        db_obj = SignApplyInfo(**sign_apply_info.dict())
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    @staticmethod
    def get_by_id(db: Session, id: int) -> Optional[SignApplyInfo]:
        """根据ID获取签到申请信息"""
        return db.query(SignApplyInfo).filter(SignApplyInfo.id == id, SignApplyInfo.isDelete != 1).first()

    @staticmethod
    def get_all(db: Session, skip: int = 0, limit: int = 100) -> List[SignApplyInfo]:
        """获取所有签到申请信息"""
        return db.query(SignApplyInfo).filter(SignApplyInfo.isDelete != 1).offset(skip).limit(limit).all()

    @staticmethod
    def get_pending_applications(db: Session) -> List[SignApplyInfo]:
        """获取所有未申请且签到时间大于0的记录"""
        return db.query(SignApplyInfo).filter(
            SignApplyInfo.isApply == 0,
            SignApplyInfo.signTime > datetime.now(),
            SignApplyInfo.isDelete != 1
        ).all()

    @staticmethod
    def update(db: Session, id: int, sign_apply_info_update: SignApplyInfoUpdate) -> Optional[SignApplyInfo]:
        """更新签到申请信息"""
        db_obj = db.query(SignApplyInfo).filter(SignApplyInfo.id == id, SignApplyInfo.isDelete != 1).first()
        if not db_obj:
            return None
        update_data = sign_apply_info_update.dict(exclude_unset=True)
        for key, value in update_data.items():
            setattr(db_obj, key, value)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    @staticmethod
    def delete(db: Session, id: int) -> bool:
        """软删除签到申请信息"""
        db_obj = db.query(SignApplyInfo).filter(SignApplyInfo.id == id, SignApplyInfo.isDelete != 1).first()
        if not db_obj:
            return False
        db_obj.isDelete = 1
        db.commit()
        return True

    @staticmethod
    def mark_as_applied(db: Session, id: int) -> bool:
        """标记为已申请"""
        db_obj = db.query(SignApplyInfo).filter(SignApplyInfo.id == id, SignApplyInfo.isDelete != 1).first()
        if not db_obj:
            return False
        db_obj.isApply = 1
        db.commit()
        return True
    @staticmethod
    def mark_as_pushed(db: Session, id: int) -> bool:
        """标记为已申请"""
        db_obj = db.query(SignApplyInfo).filter(SignApplyInfo.id == id, SignApplyInfo.isDelete != 1).first()
        if not db_obj:
            return False
        db_obj.isPush = 1
        db.commit()
        return True
